import { useCallback, useEffect, useMemo, useState } from "react";
import { useLoaderData, useSearchParams } from "react-router";
import {
  flexRender, getCoreRowModel, getPaginationRowModel, useReactTable,
  type ColumnDef, type PaginationState, type RowSelectionState
} from "@tanstack/react-table";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "~/components/ui/table";
import { Checkbox } from "~/components/ui/checkbox";
import { getPosts, type PostData } from "~/lib/jsonplaceholder";
import { Button } from "~/components/ui/button";
import type { Updater } from "@tanstack/react-query";
import type { Route } from './+types/tabledata'
import { produce } from 'immer'
export const clientLoader = async (args: Route.ClientLoaderArgs) => {
  const { request } = args;
  const { searchParams: params } = new URL(request.url);

  const page = Number(params.get("page")) || 1;
  const limit = Number(params.get("limit")) || 10;
  const data = (await getPosts(page, limit)).map(item => {

    item.uuid = crypto.randomUUID()
    return item
  })
  return {
    data,
  };
};

const columns: ColumnDef<PostData>[] = [
  {
    id: "select",
    header: ({ table }) => (
      <Checkbox
        checked={
          table.getIsAllPageRowsSelected() ||
          (table.getIsSomePageRowsSelected() && "indeterminate")
        }
        onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
        aria-label="Select all"
      />
    ),
    cell: ({ row }) => (
      <Checkbox
        checked={row.getIsSelected()}
        onCheckedChange={(value) => row.toggleSelected(!!value)}
        aria-label="Select row"
      />
    ),
    enableSorting: false,
    enableHiding: false,
  },
  {
    header: "ID",
    accessorKey: "id"
  },
  {
    header:({column})=> <Button variant="ghost" onClick={()=>column.toggleSorting(column.getIsSorted() === "asc")}>标题</Button>,
    accessorKey: "title",
    cell:({row})=>{
      return <div className="text-red-500">{row.original.title}</div>
    }
  },
  {
    header: "Body",
    accessorKey: "body"
  },

]
export default function Tabledata(props: Route.ComponentProps) {
  const [searchParams, setSearchParams] = useSearchParams({
    page: "0",
    limit: "10",
  })

  const [rowSelection, setRowSelection] = useState<RowSelectionState>({})



  const { data } = props.loaderData;



  const table = useReactTable<PostData>({
    data,
    columns,
    // getRowId: (row) => row.uuid,
    getCoreRowModel: getCoreRowModel(),
    
    onRowSelectionChange: setRowSelection,

    state: {
      rowSelection,
    }
  })


  return <div>
    <Table>
      <TableHeader>
        {table.getHeaderGroups().map((headerGroup) => (
          <TableRow key={headerGroup.id}>
            {headerGroup.headers.map((header) => {
              return (
                <TableHead key={header.id}>
                  {header.isPlaceholder
                    ? null
                    : flexRender(
                      header.column.columnDef.header,
                      header.getContext()
                    )}
                </TableHead>
              )
            })}
          </TableRow>
        ))}
      </TableHeader>
      <TableBody>
        {table.getRowModel().rows?.length ? (
          table.getRowModel().rows.map((row) => {
            return (
              <TableRow
                key={row.id}
                data-state={row.getIsSelected() && "selected"}
              >
                {row.getVisibleCells().map((cell) => {
               
                  return (
                    <TableCell key={cell.id}>
                      {flexRender(cell.column.columnDef.cell, cell.getContext())}
                    </TableCell>
                  )
                })}
              </TableRow>
            )
          })
        ) : (
          <TableRow>
            <TableCell colSpan={columns.length} className="h-24 text-center">
              没有数据
            </TableCell>
          </TableRow>
        )}
      </TableBody>
    </Table>
 
  </div>;
}